﻿using Caliburn.Micro;
using Microsoft.Win32;
using SD.Common;
using SD.Infrastructure.DTOBase;
using SD.Infrastructure.WPF.Caliburn.Aspects;
using SD.Infrastructure.WPF.Caliburn.Base;
using SD.Infrastructure.WPF.Extensions;
using SD.Infrastructure.WPF.Interfaces;
using SD.Infrastructure.WPF.Models;
using SD.IOC.Core.Mediators;
using SD.Toolkits.Excel;
using SlamDunk.MES.IAppService.DTOs.Outputs.PlanContext;
using SlamDunk.MES.IAppService.DTOs.Outputs.ResourceContext;
using SlamDunk.MES.IAppService.Interfaces;
using SlamDunk.MES.Presentation;
using SlamDunk.MES.Presentation.Maps;
using SlamDunk.MES.Presentation.Models.ExportModels;
using SlamDunk.ValueObjects.Enums;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel.Extensions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace SlamDunk.MES.Client.ViewModels.SaleOrder
{
    /// <summary>
    /// 销售订单首页视图模型
    /// </summary>
    public class IndexViewModel : ScreenBase, IPaginatable
    {
        #region # 字段及构造器

        /// <summary>
        /// 资源定义服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IResourceContract> _resourceContract;

        /// <summary>
        /// 计划管理服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IPlanContract> _planContract;

        /// <summary>
        /// 窗口管理器
        /// </summary>
        private readonly IWindowManager _windowManager;

        /// <summary>
        /// 依赖注入构造器
        /// </summary>
        public IndexViewModel(ServiceProxy<IResourceContract> resourceContract, ServiceProxy<IPlanContract> planContract, IWindowManager windowManager)
        {
            this._resourceContract = resourceContract;
            this._planContract = planContract;
            this._windowManager = windowManager;

            //默认值
            this.PageIndex = 1;
            this.PageSize = 20;
        }

        #endregion

        #region # 属性

        #region 关键字 —— string Keywords
        /// <summary>
        /// 关键字
        /// </summary>
        [DependencyProperty]
        public string Keywords { get; set; }
        #endregion

        #region 下单日期 —— DateTime? IssuedDate
        /// <summary>
        /// 下单日期
        /// </summary>
        [DependencyProperty]
        public DateTime? IssuedDate { get; set; }
        #endregion

        #region 交付日期 —— DateTime? DeliveryDate
        /// <summary>
        /// 交付日期
        /// </summary>
        [DependencyProperty]
        public DateTime? DeliveryDate { get; set; }
        #endregion

        #region 开始时间 —— DateTime? StartTime
        /// <summary>
        /// 开始时间
        /// </summary>
        [DependencyProperty]
        public DateTime? StartTime { get; set; }
        #endregion

        #region 结束时间 —— DateTime? EndTime
        /// <summary>
        /// 结束时间
        /// </summary>
        [DependencyProperty]
        public DateTime? EndTime { get; set; }
        #endregion

        #region 页码 —— int PageIndex
        /// <summary>
        /// 页码
        /// </summary>
        [DependencyProperty]
        public int PageIndex { get; set; }
        #endregion

        #region 页容量 —— int PageSize
        /// <summary>
        /// 页容量
        /// </summary>
        [DependencyProperty]
        public int PageSize { get; set; }
        #endregion

        #region 总记录数 —— int RowCount
        /// <summary>
        /// 总记录数
        /// </summary>
        [DependencyProperty]
        public int RowCount { get; set; }
        #endregion

        #region 总页数 —— int PageCount
        /// <summary>
        /// 总页数
        /// </summary>
        [DependencyProperty]
        public int PageCount { get; set; }
        #endregion

        #region 已选客户 —— EnterpriseInfo SelectedCustomer
        /// <summary>
        /// 已选客户
        /// </summary>
        [DependencyProperty]
        public EnterpriseInfo SelectedCustomer { get; set; }
        #endregion

        #region 已选审核状态 —— CheckStatus? SelectedCheckStatus
        /// <summary>
        /// 已选审核状态
        /// </summary>
        [DependencyProperty]
        public CheckStatus? SelectedCheckStatus { get; set; }
        #endregion

        #region 销售订单列表 —— ObservableCollection<Wrap<SaleOrderInfo>> SaleOrders
        /// <summary>
        /// 销售订单列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<Wrap<SaleOrderInfo>> SaleOrders { get; set; }
        #endregion

        #region 客户列表 —— ObservableCollection<EnterpriseInfo> Customers
        /// <summary>
        /// 客户列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<EnterpriseInfo> Customers { get; set; }
        #endregion

        #region 审核状态字典 —— IDictionary<string, string> CheckStatuses
        /// <summary>
        /// 审核状态字典
        /// </summary>
        [DependencyProperty]
        public IDictionary<string, string> CheckStatuses { get; set; }
        #endregion

        #endregion

        #region # 方法

        //Initializations

        #region 初始化 —— override async Task OnInitializeAsync(CancellationToken cancellationToken)
        /// <summary>
        /// 初始化
        /// </summary>
        protected override async Task OnInitializeAsync(CancellationToken cancellationToken)
        {
            IEnumerable<EnterpriseInfo> customers = await Task.Run(() => this._resourceContract.Channel.GetEnterprisesByPage(null, EnterpriseType.Customer, null, 1, int.MaxValue).Datas, cancellationToken);
            this.Customers = new ObservableCollection<EnterpriseInfo>(customers);
            this.CheckStatuses = typeof(CheckStatus).GetEnumMembers();

            await this.ReloadSaleOrders();
        }
        #endregion


        //Actions

        #region 加载销售订单列表 —— async void LoadSaleOrders()
        /// <summary>
        /// 加载销售订单列表
        /// </summary>
        public async void LoadSaleOrders()
        {
            await this.ReloadSaleOrders();
        }
        #endregion

        #region 创建销售订单 —— async void CreateSaleOrder()
        /// <summary>
        /// 创建销售订单
        /// </summary>
        public async void CreateSaleOrder()
        {
            AddViewModel viewModel = ResolveMediator.Resolve<AddViewModel>();
            await viewModel.Load(this.Customers);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            if (result == true)
            {
                await this.ReloadSaleOrders();
            }
        }
        #endregion

        #region 修改销售订单 —— async void UpdateSaleOrder()
        /// <summary>
        /// 修改销售订单
        /// </summary>
        public async void UpdateSaleOrder()
        {
            #region # 验证

            if (this.SaleOrders.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要修改的销售订单！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<SaleOrderInfo> saleOrder = this.SaleOrders.Single(x => x.IsChecked == true);

            #region # 验证

            if (saleOrder.Model.CheckStatus == CheckStatus.Checking)
            {
                MessageBox.Show("审核中的销售订单不可修改！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if (saleOrder.Model.CheckStatus == CheckStatus.Passed)
            {
                MessageBox.Show("审核通过的销售订单不可修改！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            this.Busy();

            IEnumerable<SaleOrderDetailInfo> saleOrderDetails = await Task.Run(() => this._planContract.Channel.GetSaleOrderDetails(saleOrder.Model.Id));
            UpdateViewModel viewModel = ResolveMediator.Resolve<UpdateViewModel>();
            viewModel.Load(saleOrder.Model, saleOrderDetails, this.Customers);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();

            if (result == true)
            {
                await this.ReloadSaleOrders();
            }
        }
        #endregion

        #region 删除销售订单 —— async void RemoveSaleOrders()
        /// <summary>
        /// 删除销售订单
        /// </summary>
        public async void RemoveSaleOrders()
        {
            #region # 加载勾选

            SaleOrderInfo[] checkedSaleOrders = this.SaleOrders.Where(x => x.IsChecked == true).Select(x => x.Model).ToArray();
            if (!checkedSaleOrders.Any())
            {
                MessageBox.Show("请勾选要删除的销售订单！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            MessageBoxResult result = MessageBox.Show("确定要删除吗？", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                this.Busy();

                IPlanContract planContract = this._planContract.Channel;
                await Task.Run(() => checkedSaleOrders.ForEach(authority => planContract.RemoveSaleOrder(authority.Id)));
                await this.ReloadSaleOrders();

                this.Idle();
            }
        }
        #endregion

        #region 查看销售订单 —— async void LookSaleOrder()
        /// <summary>
        /// 查看销售订单
        /// </summary>
        public async void LookSaleOrder()
        {
            #region # 验证

            if (this.SaleOrders.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要查看的销售订单！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<SaleOrderInfo> saleOrder = this.SaleOrders.Single(x => x.IsChecked == true);

            this.Busy();

            IEnumerable<SaleOrderDetailInfo> saleOrderDetails = await Task.Run(() => this._planContract.Channel.GetSaleOrderDetails(saleOrder.Model.Id));
            LookViewModel viewModel = ResolveMediator.Resolve<LookViewModel>();
            viewModel.Load(saleOrder.Model, saleOrderDetails);
            await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();
        }
        #endregion

        #region 提交审核销售订单 —— async void SubmitSaleOrders()
        /// <summary>
        /// 提交审核销售订单
        /// </summary>
        public async void SubmitSaleOrders()
        {
            #region # 加载勾选

            SaleOrderInfo[] checkedSaleOrders = this.SaleOrders.Where(x => x.IsChecked == true).Select(x => x.Model).ToArray();
            if (!checkedSaleOrders.Any())
            {
                MessageBox.Show("请勾选要提交审核的销售订单！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            MessageBoxResult result = MessageBox.Show("确定要提交审核吗？", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning);
            if (result == MessageBoxResult.Yes)
            {
                this.Busy();

                IPlanContract planContract = this._planContract.Channel;
                await Task.Run(() => planContract.SubmitSaleOrders(checkedSaleOrders.Select(x => x.Id)));
                await this.ReloadSaleOrders();

                this.Idle();
            }
        }
        #endregion

        #region 审核销售订单 —— async void CheckSaleOrder()
        /// <summary>
        /// 审核销售订单
        /// </summary>
        public async void CheckSaleOrder()
        {
            #region # 验证

            if (this.SaleOrders.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要审核的销售订单！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<SaleOrderInfo> saleOrder = this.SaleOrders.Single(x => x.IsChecked == true);

            #region # 验证

            if (saleOrder.Model.CheckStatus != CheckStatus.Checking)
            {
                MessageBox.Show("只有审核中的销售订单可以审核！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            this.Busy();

            IEnumerable<SaleOrderDetailInfo> saleOrderDetails = await Task.Run(() => this._planContract.Channel.GetSaleOrderDetails(saleOrder.Model.Id));
            CheckViewModel viewModel = ResolveMediator.Resolve<CheckViewModel>();
            viewModel.Load(saleOrder.Model, saleOrderDetails);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();

            if (result == true)
            {
                await this.ReloadSaleOrders();
            }
        }
        #endregion

        #region 打印销售订单 —— async void PrintSaleOrder()
        /// <summary>
        /// 打印销售订单
        /// </summary>
        public async void PrintSaleOrder()
        {
            #region # 验证

            if (this.SaleOrders.Count(x => x.IsChecked == true) != 1)
            {
                MessageBox.Show("请勾选一条要打印的销售订单！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            #endregion

            Wrap<SaleOrderInfo> saleOrder = this.SaleOrders.Single(x => x.IsChecked == true);

            this.Busy();

            IEnumerable<SaleOrderDetailInfo> saleOrderDetails = await Task.Run(() => this._planContract.Channel.GetSaleOrderDetails(saleOrder.Model.Id));
            PrintViewModel viewModel = ResolveMediator.Resolve<PrintViewModel>();
            viewModel.Load(saleOrder.Model, saleOrderDetails);
            await this._windowManager.ShowDialogAsync(viewModel);

            this.Idle();
        }
        #endregion

        #region 导出销售订单 —— async void ExportSaleOrders()
        /// <summary>
        /// 导出销售订单
        /// </summary>
        public async void ExportSaleOrders()
        {
            string keywords = this.Keywords;
            Guid? customerId = this.SelectedCustomer?.Id;
            DateTime? issuedDate = this.IssuedDate;
            DateTime? deliveryDate = this.DeliveryDate;
            CheckStatus? checkStatus = this.SelectedCheckStatus;
            DateTime? startTime = this.StartTime;
            DateTime? endTime = this.EndTime;
            PageModel<SaleOrderInfo> pageModel = await Task.Run(() => this._planContract.Channel.GetSaleOrdersByPage(keywords, customerId, issuedDate, deliveryDate, checkStatus, startTime, endTime, 1, int.MaxValue));

            SaleOrderEm[] saleOrderEms = pageModel.Datas.Select(x => x.ToExportView()).ToArray();
            if (!saleOrderEms.Any())
            {
                MessageBox.Show("导出数据为空，不能进行导出！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = Constants.ExeclFileExtensionsFilter,
                FileName = $"销售订单_{DateTime.Now.ToString(Constants.ExportFileTimeFormat)}",
                AddExtension = true,
                RestoreDirectory = true
            };
            if (saveFileDialog.ShowDialog() == true)
            {
                string filePath = saveFileDialog.FileName;
                ExcelWriter.WriteFile(saleOrderEms, filePath);
            }
        }
        #endregion

        #region 全选 —— void CheckAll()
        /// <summary>
        /// 全选
        /// </summary>
        public void CheckAll()
        {
            this.SaleOrders.ForEach(x => x.IsChecked = true);
        }
        #endregion

        #region 取消全选 —— void UncheckAll()
        /// <summary>
        /// 取消全选
        /// </summary>
        public void UncheckAll()
        {
            this.SaleOrders.ForEach(x => x.IsChecked = false);
        }
        #endregion


        //Private

        #region 加载销售订单列表 —— async Task ReloadSaleOrders()
        /// <summary>
        /// 加载销售订单列表
        /// </summary>
        private async Task ReloadSaleOrders()
        {
            this.Busy();

            string keywords = this.Keywords;
            Guid? customerId = this.SelectedCustomer?.Id;
            DateTime? issuedDate = this.IssuedDate;
            DateTime? deliveryDate = this.DeliveryDate;
            CheckStatus? checkStatus = this.SelectedCheckStatus;
            DateTime? startTime = this.StartTime;
            DateTime? endTime = this.EndTime;

            PageModel<SaleOrderInfo> pageModel = await Task.Run(() => this._planContract.Channel.GetSaleOrdersByPage(keywords, customerId, issuedDate, deliveryDate, checkStatus, startTime, endTime, this.PageIndex, this.PageSize));
            this.RowCount = pageModel.RowCount;
            this.PageCount = pageModel.PageCount;

            IEnumerable<Wrap<SaleOrderInfo>> wrapModels = pageModel.Datas.Select(x => x.Wrap());
            this.SaleOrders = new ObservableCollection<Wrap<SaleOrderInfo>>(wrapModels);

            this.Idle();
        }
        #endregion

        #endregion
    }
}
